#include "ts.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <memory.h>
#include <QtCore>

void ts_parse(char *abuf, ts_t *ts)
{
    int i_skip = 0, adap_len = 0;
    int tmp8;
    long tmp16;
    unsigned char buf[188];

    memcpy(buf, abuf, 188*sizeof(char));
    memset(ts, 0, sizeof(ts_t));
    pes_t *pes = &(ts->pes);
    ts->sync_byte = 0x47;
    ts->tei = ((buf[1] & 0x80) >> 7);
    ts->pusi = ((buf[1] & 0x40) >> 6);
    ts->tp = ((buf[1] & 0x20) >> 5);
    ts->PID = ((buf[1] & 0x1f) << 4) + buf[2];
    ts->tsc = ((buf[3] & 0xC0) >> 6);
    ts->afc = ((buf[3] & 0x30) >> 4);
    ts->cc = (buf[3] & 0x0f);
    i_skip = 4;
    if (ts->afc&0x10) {
        adap_len = buf[i_skip];
        i_skip += adap_len;
    }
    if ((ts->afc&0x01) && (ts->pusi)) {
#if 0
        if (ts->payload_unit_start_indicator) {
            i_skip++;
        }
#endif
        i_skip += 2;
        if (buf[i_skip] == 1)
            i_skip++;
        pes->stream_id = buf[i_skip++];
        pes->PESplen = (buf[i_skip] << 4) + buf[i_skip+1];
        i_skip += 3;
        tmp8 = buf[i_skip++];
        pes->PDflags = ((tmp8 & 0xC0) >> 6);
        pes->PEShlen = buf[i_skip++];
        if (pes->PDflags == 2) {
            tmp8 = buf[i_skip++];
            pes->pts = (((tmp8 & 0x0E) >> 1) << 30);
            tmp16 = (buf[i_skip] << 8) + buf[i_skip+1];
            i_skip += 2;
            pes->pts += (((tmp16 & 0xFFFE) >> 1) << 15);
            tmp16 = (buf[i_skip] << 8) + buf[i_skip+1];
            i_skip += 2;
            pes->pts += ((tmp16 & 0xFFFE) >> 1);
        }
        if (pes->PDflags == 3) {
            tmp8 = buf[i_skip++];
            pes->pts = (((tmp8 & 0x0E) >> 1) << 30);
            tmp16 = (buf[i_skip] << 8) + buf[i_skip+1];
            i_skip += 2;
            pes->pts += (((tmp16 & 0xFFFE) >> 1) << 15);
            tmp16 = (buf[i_skip] << 8) + buf[i_skip+1];
            i_skip += 2;
            pes->pts += ((tmp16 & 0xFFFE) >> 1);
//
            tmp8 = buf[i_skip++];
            pes->dts = (((tmp8 & 0x0E) >> 1) << 30);
            tmp16 = (buf[i_skip] << 8) + buf[i_skip+1];
            i_skip += 2;
            pes->dts += (((tmp16 & 0xFFFE) >> 1) << 15);
            tmp16 = (buf[i_skip] << 8) + buf[i_skip+1];
            i_skip += 2;
            pes->dts += ((tmp16 & 0xFFFE) >> 1);
        }
    }
    return;
}
